using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

/// <summary>
/// Wraps the post around a pre-defined template
/// </summary>
[Extension("Wraps a post around a pre-defined template", "1.0", "Joe Kaiser")]
public class PostTemplate
{
    /// <summary>
    /// Initializes a new instance of the <see cref="PostTemplate"/> class.
    /// </summary>
    public PostTemplate()
    {
        Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);
    }

    /// <summary>
    /// Handles the Serving event of the Post control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="BlogEngine.Core.ServingEventArgs"/> instance containing the event data.</param>
    void Post_Serving(object sender, ServingEventArgs e)
    {
        if (e.Location != ServingLocation.Feed)
        {
            ProcessPost(sender, e);
        }
    }

    /// <summary>
    /// Processes the post and wraps it in the template.
    /// </summary>
    /// <param name="sender">The sender (post).</param>
    /// <param name="e">The <see cref="BlogEngine.Core.SavedEventArgs"/> instance containing the event data.</param>
    private void ProcessPost(object sender, ServingEventArgs e)
    {
        Post p = sender as Post;

        string file = string.Format("{0}PostTemplate.txt", HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation));

        if (File.Exists((file)))
        {
            using (StreamReader reader = new StreamReader(file))
            {
                string template = reader.ReadToEnd();
                p.Content = template.Replace("{content}", p.Content);
            }
        }

    }
}
